package service

import (
	"api/app/auth/models"
	"api/config"
	"api/libs/errs"
	"api/public/access"
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"gitee.com/dreamwood/ez"
	"io"
	"time"
)

func GenPass(password string, salt string) string {
	m5 := md5.New()
	_, _ = io.WriteString(m5, password+salt)
	return hex.EncodeToString(m5.Sum(nil))
}

func Login(user *models.User) {
	//用户信息写入缓存
	SetUserCache2Redis(user)
}

func GetUserFromRedis(token string) *models.User {
	redis := config.GetRedis()
	rst := redis.Get(access.CreateUserRedisKey(token))
	if errs.Try(rst.Err()) {
		ez.Debug(rst.Err())
		return nil
	}
	ez.Debug(rst.String())
	return nil
}

func SetUserCache2Redis(user *models.User) {
	redis := config.GetRedis()
	rst := redis.Set(access.CreateUserRedisKey(user.Token), user.ToBytes(), 3*time.Hour)
	errs.Try(rst.Err())
}

func CreateUserToken(user *models.User) (token string) {

	//取出Roles,如果为空，不允许访问
	roles := make([]int, 0)
	for _, role := range user.Roles {
		roles = append(roles, role.Id)
	}
	if len(roles) == 0 {
		return
	}
	//写入Id，写入当前时间戳
	originData := fmt.Sprintf("%d %d", user.Id, time.Now().Unix())

	//从三位开始是角色ID··
	for _, role := range roles {
		originData += fmt.Sprintf(" %d", role)
	}
	//todo 这里应该对每个服务使用不同的VI以避免VI泄露引起的安全问题
	token = ez.AesEncrypt(originData, config.GetCore().Vi)
	token = base64.StdEncoding.EncodeToString([]byte(token))
	return
}

func GetUserByDepartments(ids []int) (users []*models.User) {
	users = make([]*models.User, 0)
	if len(ids) == 0 {
		return
	}
	userCrud := models.NewUserCrud()
	userFinds, e := userCrud.FindBy(ez.M{
		"departmentId__in": ids,
	}, nil, 0, 0)
	if ez.PrintError(e) {
		return
	} else {
		users = userFinds
	}
	return
}
func GetUserByJobs(ids []int) (users []*models.User) {
	users = make([]*models.User, 0)
	if len(ids) == 0 {
		return
	}
	userCrud := models.NewUserCrud()
	userFinds, e := userCrud.FindBy(ez.M{
		"jobs.id__in": ids,
	}, nil, 0, 0)
	if ez.PrintError(e) {
		return
	} else {
		users = userFinds
	}
	return
}
func GetUserByRoles(ids []int) (users []*models.User) {
	users = make([]*models.User, 0)
	if len(ids) == 0 {
		return
	}
	userCrud := models.NewUserCrud()
	userFinds, e := userCrud.FindBy(ez.M{
		"roles.id__in": ids,
	}, nil, 0, 0)
	if ez.PrintError(e) {
		return
	} else {
		users = userFinds
	}
	return
}
func GetUserByIds(ids []int) (users []*models.User) {
	users = make([]*models.User, 0)
	if len(ids) == 0 {
		return
	}
	userCrud := models.NewUserCrud()
	userFinds, e := userCrud.FindBy(ez.M{
		"id__in": ids,
	}, nil, 0, 0)
	if ez.PrintError(e) {
		return
	} else {
		users = userFinds
	}
	return
}

func UserDistinct(users ...[]*models.User) []*models.User {
	tmp := make(map[int]*models.User)
	for _, userSlice := range users {
		for _, user := range userSlice {
			if user.Id == 0 {
				continue
			}
			tmp[user.Id] = user
		}
	}
	mergedUsers := make([]*models.User, 0)
	for _, user := range tmp {
		mergedUsers = append(mergedUsers, user)
	}
	return mergedUsers
}
